import 'package:animated_transitions/animated_transitions.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:redux/redux.dart';
import 'package:vamos/core/index.dart';
import '../../core/widgets/report_dialog.dart';
import '../video/local_video_player_page.dart';
import '../profile/other_profile_page.dart';

/// 社交动态详情界面
class VamosSocialDetailInterface extends StatefulWidget {
  final SocialPostEntity post;

  const VamosSocialDetailInterface({super.key, required this.post});

  @override
  State<VamosSocialDetailInterface> createState() =>
      _VamosSocialDetailInterfaceState();
}

class _VamosSocialDetailInterfaceState
    extends State<VamosSocialDetailInterface> {
  late ReduxSocialManager _socialManager;
  late ReduxUserManager _userManager;
  final TextEditingController _commentController = TextEditingController();

  // 点赞状态管理
  bool _isPostLiked = false;

  @override
  void initState() {
    super.initState();
    _socialManager = serviceLocator<ReduxSocialManager>();
    _userManager = serviceLocator<ReduxUserManager>();

    // 初始化点赞状态
    _initializeLikeState();
  }

  /// 初始化点赞状态
  void _initializeLikeState() {
    final currentUser = _userManager.getCurrentUser();
    if (currentUser != null) {
      final appState = _socialManager.store.state;
      final postList =
          appState.socialState.postCollection
              .where((p) => p.postId == widget.post.postId)
              .toList();
      final currentPost = postList.isNotEmpty ? postList.first : null;

      if (currentPost != null) {
        _isPostLiked = currentPost.likedUserIds.contains(currentUser.uniqueId);
      }
    }
  }

  bool _isUserLoggedIn() => _userManager.getCurrentUser() != null;

  @override
  void dispose() {
    _commentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // 背景
          Container(
            width: double.infinity,
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my_background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: Column(
                children: [
                  _buildTopNavigationBar(),
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          _buildMediaArea(),
                          _buildPostHeaderInfo(),
                          _buildCommentsSection(),
                        ],
                      ),
                    ),
                  ),
                  _buildCommentInput(),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          Icon(
            Icons.arrow_back,
            color: Colors.white,
            size: 26.w,
          ).inkWell(onTap: () => Navigator.pop(context)),
          Expanded(
            child:
                Text('DETAILS')
                    .fontSize(20.sp)
                    .textColor(Colors.white)
                    .fontFamily(
                      GoogleFonts.poppins(
                        fontWeight: FontWeight.w700,
                      ).fontFamily!,
                    )
                    .center(),
          ),
          Image.asset(
            'assets/images/report2.png',
            width: 24.w,
            height: 24.w,
          ).inkWell(onTap: _handlePostReport),
        ],
      ),
    );
  }

  Widget _buildMediaArea() {
    final isImage =
        widget.post.mediaType == PostMediaType.image &&
        widget.post.mediaUrl != null;
    final isVideo =
        widget.post.mediaType == PostMediaType.video &&
        widget.post.thumbnailUrl != null;

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      child: AspectRatio(
        aspectRatio: 343 / 282,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12.r),
          child: Stack(
            children: [
              if (isImage)
                Image.asset(
                  widget.post.mediaUrl!,
                  width: double.infinity,
                  height: double.infinity,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stack) {
                    return Container(color: Colors.grey[800]);
                  },
                )
              else if (isVideo)
                Image.asset(
                  widget.post.thumbnailUrl!,
                  width: double.infinity,
                  height: double.infinity,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stack) {
                    return Container(color: Colors.grey[800]);
                  },
                )
              else
                Container(color: Colors.grey[800]),

              if (widget.post.mediaType == PostMediaType.video)
                SizedBox(
                  width: double.infinity,
                  height: double.infinity,
                  child: Icon(
                    Icons.play_circle_filled,
                    size: 64.w,
                    color: Colors.white.withOpacity(0.9),
                  ).center().inkWell(onTap: _navigateToVideoPlayer),
                ),
            ],
          ),
        ),
      ),
    );
  }

  /// 动态头部信息（用户+文案+计数）
  Widget _buildPostHeaderInfo() {
    final author = _userManager.getUserById(widget.post.authorId);

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.3),
        borderRadius: BorderRadius.circular(24.r),
        border: Border.all(color: Colors.white.withOpacity(0.4), width: 1.w),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                width: 53.w,
                height: 53.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(color: Colors.white, width: 1.5.w),
                ),
                child: ClipOval(
                  child:
                      author != null
                          ? Image.asset(
                            author.profileImage,
                            width: 44.w,
                            height: 44.w,
                            fit: BoxFit.cover,
                            errorBuilder: (context, error, stack) {
                              return Icon(
                                Icons.person,
                                size: 20.w,
                                color: Colors.grey[600],
                              ).center();
                            },
                          )
                          : Icon(
                            Icons.person,
                            size: 20.w,
                            color: Colors.grey[600],
                          ).center(),
                ),
              ).inkWell(onTap: () => _navigateToUserProfile(author)),
              SizedBox(width: 12.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(author?.displayName ?? 'Unknown User')
                        .fontSize(14.sp)
                        .textColor(Colors.white)
                        .fontFamily(
                          GoogleFonts.poppins(
                            fontWeight: FontWeight.w600,
                          ).fontFamily!,
                        ),
                    SizedBox(height: 4.h),
                    Text(author?.personalBio ?? 'No bio available')
                        .fontSize(10.sp)
                        .textColor(Colors.white)
                        .fontFamily(
                          GoogleFonts.poppins(
                            fontWeight: FontWeight.w300,
                          ).fontFamily!,
                        ),
                  ],
                ),
              ),
            ],
          ),

          SizedBox(height: 12.h),

          Text(widget.post.content)
              .fontSize(14.sp)
              .textColor(Colors.white)
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily!,
              ),

          SizedBox(height: 12.h),

          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Row(
                children: [
                  Image.asset(
                    _isPostLiked
                        ? 'assets/images/like_fill.png'
                        : 'assets/images/like.png',
                    width: 18.w,
                    height: 18.w,
                  ).inkWell(onTap: _handlePostLike),
                  SizedBox(width: 6.w),
                  StreamBuilder(
                    stream: _socialManager.store.onChange,
                    builder: (context, snapshot) {
                      final appState = _socialManager.store.state;
                      final list =
                          appState.socialState.postCollection
                              .where((p) => p.postId == widget.post.postId)
                              .toList();
                      final current = list.isNotEmpty ? list.first : null;
                      final likeCount =
                          current?.likeCount ?? widget.post.likeCount;
                      return Text(
                        '$likeCount',
                      ).fontSize(14.sp).textColor(Colors.white);
                    },
                  ),
                ],
              ),

              SizedBox(width: 20.w),

              Row(
                children: [
                  Image.asset(
                    'assets/images/comment.png',
                    width: 18.w,
                    height: 18.w,
                  ),
                  SizedBox(width: 6.w),
                  StreamBuilder(
                    stream: _socialManager.store.onChange,
                    builder: (context, snapshot) {
                      final appState = _socialManager.store.state;
                      final list =
                          appState.socialState.postCollection
                              .where((p) => p.postId == widget.post.postId)
                              .toList();
                      final current = list.isNotEmpty ? list.first : null;
                      final commentCount =
                          current?.commentCount ?? widget.post.commentCount;
                      return Text(
                        '$commentCount',
                      ).fontSize(14.sp).textColor(Colors.white);
                    },
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 评论列表
  Widget _buildCommentsSection() {
    return StreamBuilder(
      stream: _socialManager.store.onChange,
      builder: (context, snapshot) {
        final appState = _socialManager.store.state;
        final comments =
            appState.socialState.commentCollection
                .where((c) => c.postId == widget.post.postId)
                .toList();

        return Container(
          width: double.infinity,
          margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          padding: EdgeInsets.all(12.w),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.3),
            borderRadius: BorderRadius.circular(24.r),
            border: Border.all(
              color: Colors.white.withOpacity(0.4),
              width: 1.w,
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('${comments.length} Comments In Total')
                  .fontSize(16.sp)
                  .textColor(Colors.white)
                  .fontFamily(
                    GoogleFonts.poppins(
                      fontWeight: FontWeight.w600,
                    ).fontFamily!,
                  ),
              SizedBox(height: 12.h),
              if (comments.isEmpty)
                _buildEmptyCommentsState()
              else
                ...comments.map(_buildCommentItem).toList(),
            ],
          ),
        );
      },
    );
  }

  /// 构建空评论状态
  Widget _buildEmptyCommentsState() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 40.h),
      child: Column(
        children: [
          Image.asset(
            'assets/images/empty.png',
            width: 80.w,
            height: 80.w,
            fit: BoxFit.contain,
          ),
          SizedBox(height: 16.h),
          Text('No comments yet')
              .fontSize(14.sp)
              .textColor(Colors.white.withOpacity(0.7))
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily!,
              ),
          SizedBox(height: 4.h),
          Text('Be the first to comment!')
              .fontSize(12.sp)
              .textColor(Colors.white.withOpacity(0.5))
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w300).fontFamily!,
              ),
        ],
      ),
    );
  }

  Widget _buildCommentItem(PostCommentEntity comment) {
    final author = _userManager.getUserById(comment.authorId);
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 36.w,
            height: 36.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Colors.white, width: 1.w),
            ),
            child: ClipOval(
              child:
                  author != null
                      ? Image.asset(
                        author.profileImage,
                        width: 36.w,
                        height: 36.w,
                        fit: BoxFit.cover,
                      )
                      : Icon(
                        Icons.person,
                        size: 16.w,
                        color: Colors.grey[600],
                      ).center(),
            ),
          ).inkWell(onTap: () => _navigateToUserProfile(author)),
          SizedBox(width: 10.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(author?.displayName ?? 'Unknown User')
                    .fontSize(12.sp)
                    .textColor(Colors.white)
                    .fontFamily(
                      GoogleFonts.poppins(
                        fontWeight: FontWeight.w600,
                      ).fontFamily!,
                    ),
                SizedBox(height: 2.h),
                Text(
                      author?.personalBio ?? 'No bio available',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    )
                    .fontSize(8.sp)
                    .textColor(Colors.white.withOpacity(0.7))
                    .fontFamily(
                      GoogleFonts.poppins(
                        fontWeight: FontWeight.w400,
                      ).fontFamily!,
                    ),
                SizedBox(height: 4.h),
                Text(comment.content)
                    .fontSize(12.sp)
                    .textColor(Colors.white)
                    .fontFamily(
                      GoogleFonts.poppins(
                        fontWeight: FontWeight.w400,
                      ).fontFamily!,
                    ),
              ],
            ),
          ),
          SizedBox(width: 8.w),
          Image.asset(
            'assets/images/report2.png',
            width: 16.w,
            height: 16.w,
          ).inkWell(onTap: () => _handleCommentReport(comment)),
        ],
      ),
    );
  }

  /// 底部评论输入框
  Widget _buildCommentInput() {
    return Container(
      padding: EdgeInsets.all(16.w),
      child: Container(
        height: 40.h,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(6.r),
        ),
        child: Row(
          children: [
            Expanded(
              child: TextField(
                controller: _commentController,
                style: TextStyle(color: Colors.black, fontSize: 14.sp),
                decoration: InputDecoration(
                  hintText: 'Input Content',
                  hintStyle: TextStyle(
                    color: Colors.grey[500],
                    fontSize: 14.sp,
                  ),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 0.h,
                  ),
                  isDense: true,
                ),
                textAlignVertical: TextAlignVertical.center,
              ),
            ),
            Padding(
              padding: EdgeInsets.only(right: 8.w),
              child: Image.asset(
                'assets/images/send_answer.png',
                width: 24.w,
                height: 24.w,
              ).inkWell(onTap: _submitComment),
            ),
          ],
        ),
      ),
    );
  }

  /// 提交评论
  void _submitComment() async {
    final text = _commentController.text.trim();
    if (text.isEmpty) return;

    if (!_isUserLoggedIn()) {
      VamosLoginRequiredDialog.showLoginRequiredDialog(context);
      return;
    }

    final currentUser = _userManager.getCurrentUser();
    if (currentUser == null) return;

    try {
      final newComment = PostCommentEntity(
        commentId: 'post_comment_${DateTime.now().millisecondsSinceEpoch}',
        postId: widget.post.postId,
        authorId: currentUser.uniqueId,
        content: text,
        commentTime: DateTime.now(),
      );

      final success = await _socialManager.addComment(newComment);
      if (success) {
        _commentController.clear();
        setState(() {});
        NotificationUtils.showSuccess(context, message: 'Reply Success.');
      } else {
        NotificationUtils.showError(context, message: 'Reply Failed.');
      }
    } catch (e) {
      NotificationUtils.showError(context, message: 'Reply Failed: $e');
    }
  }

  /// 举报动态
  void _handlePostReport() {
    showVamosReportDialog(
      context: context,
      title: 'Report Post',
      subtitle: 'Please select a reason for reporting this post.',
      onReportSubmitted: (VamosReportOption option) {
        _deletePostAndExit();
      },
    );
  }

  /// 删除动态并返回
  void _deletePostAndExit() async {
    try {
      final success = await _socialManager.deletePost(widget.post.postId);
      if (success) {
        NotificationUtils.showSuccess(
          context,
          message: 'You won\'t see this again.',
        );
        Navigator.pop(context);
      } else {
        NotificationUtils.showError(context, message: 'Failed to report post.');
      }
    } catch (e) {
      NotificationUtils.showError(context, message: 'Error reporting post: $e');
    }
  }

  /// 举报评论（删除该评论）
  void _handleCommentReport(PostCommentEntity comment) {
    showVamosReportDialog(
      context: context,
      title: 'Report Comment',
      subtitle: 'Please select a reason for reporting this comment.',
      onReportSubmitted: (VamosReportOption option) {
        _deleteSingleComment(comment);
      },
    );
  }

  void _deleteSingleComment(PostCommentEntity comment) async {
    try {
      final success = await _socialManager.deleteComment(comment.commentId);

      if (success) {
        setState(() {
          // 触发UI更新
        });

        NotificationUtils.showSuccess(
          context,
          message: 'You won\'t see this again.',
        );
      } else {
        NotificationUtils.showError(
          context,
          message: 'Failed to report comment.',
        );
      }
    } catch (e) {
      NotificationUtils.showError(
        context,
        message: 'Error reporting comment: $e',
      );
    }
  }

  /// 处理动态点赞
  void _handlePostLike() async {
    // 检查用户是否登录
    if (!_isUserLoggedIn()) {
      VamosLoginRequiredDialog.showLoginRequiredDialog(context);
      return;
    }

    final currentUser = _userManager.getCurrentUser();
    if (currentUser == null) return;

    try {
      setState(() {
        _isPostLiked = !_isPostLiked;
      });

      if (_isPostLiked) {
        // 点赞
        final success = await _socialManager.likePost(
          widget.post.postId,
          currentUser.uniqueId,
        );
        if (success) {
          // 点赞成功
        } else {
          // 回滚状态
          setState(() {
            _isPostLiked = !_isPostLiked;
          });
        }
      } else {
        // 取消点赞
        final success = await _socialManager.unlikePost(
          widget.post.postId,
          currentUser.uniqueId,
        );
        if (success) {
          // 取消点赞成功
        } else {
          // 回滚状态
          setState(() {
            _isPostLiked = !_isPostLiked;
          });
        }
      }
    } catch (e) {
      // 回滚状态
      setState(() {
        _isPostLiked = !_isPostLiked;
      });
    }
  }

  /// 跳转到用户主页
  void _navigateToUserProfile(UserDataEntity? user) {
    if (user == null) return;

    // 检查是否是当前用户，如果是则不跳转
    final currentUser = _userManager.getCurrentUser();
    if (currentUser != null && currentUser.uniqueId == user.uniqueId) {
      return;
    }

    // 跳转到其他用户主页
    Navigator.of(context).push(
      TransitionPageRoute(
        builder:
            (context) => StoreProvider<AppState>(
              store: serviceLocator<Store<AppState>>(),
              child: VamosOtherProfileInterface(user: user),
            ),
        transitionAnimation: BrushStrokeTransition(
          direction: TransitionDirection.right,
          colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
        ),
      ),
    );
  }

  /// 跳转视频播放
  void _navigateToVideoPlayer() {
    if (widget.post.mediaType == PostMediaType.video &&
        widget.post.mediaUrl != null) {
      Navigator.of(context).push(
        MaterialPageRoute(
          builder:
              (context) => VamosLocalVideoPlayerInterface(
                videoPath: widget.post.mediaUrl!,
                title:
                    widget.post.content.isNotEmpty
                        ? widget.post.content
                        : 'Video',
                description: widget.post.content,
              ),
        ),
      );
    } else {
      NotificationUtils.showInfo(context, message: 'Video not available.');
    }
  }
}
